const http = require('http')
const url = require('url')
const webhookHandler = require('./webhookHandler')
const now = require('./now')

function buildRequestHandler (info) {

  return function (request, response) {
    logRequest(request)

    let data = ''
    let path = url.parse(request.url).pathname
    path = path.substring(1)

    if (path === '') {
      response.end(serverInfo())
      return
    }

    request.on('data', function (chunk) {
      data += chunk;
    })

    request.on('end', function () {
      logData(data)
      try {
        data = JSON.parse(data)
      } catch (err) {
        response.writeHead(400)
        response.end('请求消息体的JSON格式异常！')
      }
      let body = webhookHandler(path, data, request, response)
      response.writeHead(body[0])
      response.end(body[1])
    })
  }

  function serverInfo () {
    const data = {
      "zen": "git-hook旨在提供快捷、灵活、安全、可靠的WebHook体验",
      "version": info.version,
      "license": info.license
    }
    return `git-hook:
    zen: ${data.zen}
    version: ${data.version}
    license: ${data.license}`
  }

  function logRequest(request) {
    console.log(`### handle new request at ${now()} ###`)
    // console.log('request: ', request)
  }

  function logData(data) {
    // console.log('request data: ', data)
  }

}

class Server {

  constructor (port, info = {}) {
    this.port = port
    this.info = info
  }

  start() {
    http.createServer(buildRequestHandler(this.info)).listen(this.port, (err) => {
      if (err) {
        return console.log('something bad happened', err)
      } else {
        console.log(`server is listening on ${this.port}`)
      }
    })
  }

  _requestHandler(request, response) {
  }

  _serverInfo () {
  }

}

module.exports = Server
